/*
 * sdram.c
 *
 *  Created on: Apr 22, 2025
 *      Author: Van
 */

#include "sdram.h"
#include "shell_port.h"

extern SDRAM_HandleTypeDef hsdram1;

uint8_t SDRAM_Send_Cmd(uint8_t bankx,uint8_t cmd,uint8_t refresh,uint16_t regval)//参数=BANK号 命令 刷新次数 寄存器值
{
	uint32_t target_bank=1;
	FMC_SDRAM_CommandTypeDef Command;
	if(bankx==1) target_bank=FMC_SDRAM_CMD_TARGET_BANK1;
	else if(bankx==2) target_bank=FMC_SDRAM_CMD_TARGET_BANK2;
	Command.CommandMode=cmd;
	Command.CommandTarget=target_bank;
	Command.AutoRefreshNumber=refresh;
	Command.ModeRegisterDefinition=regval;
	if(HAL_SDRAM_SendCommand(&hsdram1,&Command,0X1000)==HAL_OK)

	{
		return 0;
	}
	else return 1;
}






void SDRAM_Initialization_Sequence(SDRAM_HandleTypeDef *hsdram)
{
	uint32_t temp=0;

	SDRAM_Send_Cmd(1,FMC_SDRAM_CMD_CLK_ENABLE,1,0);				//使能时钟
	HAL_Delay(1);												//延时至少200us
	SDRAM_Send_Cmd(1,FMC_SDRAM_CMD_PALL,1,0);					//所有BANK预充电
	SDRAM_Send_Cmd(1,FMC_SDRAM_CMD_AUTOREFRESH_MODE,8,0);		//插入8个自动刷新周期
	temp = (uint32_t)SDRAM_MODEREG_BURST_LENGTH_1 | SDRAM_MODEREG_BURST_TYPE_SEQUENTIAL | SDRAM_MODEREG_CAS_LATENCY_2 | SDRAM_MODEREG_OPERATING_MODE_STANDARD | SDRAM_MODEREG_WRITEBURST_MODE_SINGLE;//配置SDRAM模式寄存器
	SDRAM_Send_Cmd(1,FMC_SDRAM_CMD_LOAD_MODE,1,temp);			//配置SDRAM模式寄存器(注意SDRAM_MODEREG_CAS_LATENCY_3需要与cube里的CAS_LATENCY配置对应)

	//配置stm32 FMC的sdram控制器的自动刷新周期
    //Refresh rate = (SDRAM refresh rate  * SDRAM clock frequency) - 20
    //SDRAM refresh rate = SDRAM refresh period / Number of rows
    //SDRAM refresh rate = 64ms / 8196(rows) = 7.81us
    //Refresh rate = 7.81us * 120Mhz  - 20 = 917(cycles)
	HAL_SDRAM_ProgramRefreshRate(hsdram,917);
}




void fsmc_sdram_test(void)
{
	uint32_t i=0;
	uint32_t temp=0;
	uint32_t sval=0;

	for(i=0;i<32*1024*1024;i+=16*1024)
	{
		*(uint32_t*)(Bank5_SDRAM_ADDR+i)=temp;
		temp++;
	}

 	for(i=0;i<32*1024*1024;i+=16*1024)
	{
  		temp=*(uint32_t*)(Bank5_SDRAM_ADDR+i);
		if(i==0)sval=temp;
 		else if(temp<=sval)
		{
			break;
		}
		printf("SDRAM Capacity:%luKB\r\n",(uint32_t)((temp+1-sval)*16));
 	}
}



















